import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { bookingApi } from "../api";
import {
  createBookingWorker,
  formatBookingConfig,
  parseBookingResult,
} from "../utils/booking";

export const useBookingStore = defineStore("booking", () => {
  // 状态
  const bookingTasks = ref([]);
  const activeWorkers = ref({});
  const bookingHistory = ref([]);
  const loading = ref(false);

  // 计算属性
  const activeTaskCount = computed(() => bookingTasks.value.length);
  const successCount = computed(
    () => bookingHistory.value.filter((item) => item.success).length
  );
  const failureCount = computed(
    () => bookingHistory.value.filter((item) => !item.success).length
  );
  const successRate = computed(() => {
    const total = bookingHistory.value.length;
    return total > 0 ? ((successCount.value / total) * 100).toFixed(2) : "0.00";
  });

  // 方法
  const startBooking = async (config) => {
    try {
      loading.value = true;

      // 创建抢票任务
      const response = await bookingApi.startBooking(config);
      const taskId = response.data.taskId;

      // 格式化配置
      const formattedConfig = formatBookingConfig(config);

      // 创建Web Worker
      const worker = createBookingWorker(formattedConfig);

      // 监听Worker消息
      worker.onmessage = (e) => {
        const { type, data, error } = e.data;

        switch (type) {
          case "success":
            handleBookingSuccess(taskId, data);
            break;
          case "error":
            handleBookingError(taskId, error);
            break;
          case "retry":
            handleBookingRetry(taskId, data);
            break;
        }
      };

      // 保存任务和Worker
      bookingTasks.value.push({
        id: taskId,
        config: formattedConfig,
        status: "running",
        startTime: new Date().toISOString(),
      });
      activeWorkers.value[taskId] = worker;

      // 开始抢票
      worker.postMessage({ type: "start", data: formattedConfig });

      return taskId;
    } catch (error) {
      console.error("启动抢票任务失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const stopBooking = async (taskId) => {
    try {
      loading.value = true;

      // 停止Worker
      const worker = activeWorkers.value[taskId];
      if (worker) {
        worker.postMessage({ type: "stop" });
        worker.terminate();
        delete activeWorkers.value[taskId];
      }

      // 更新任务状态
      const taskIndex = bookingTasks.value.findIndex(
        (task) => task.id === taskId
      );
      if (taskIndex > -1) {
        bookingTasks.value[taskIndex].status = "stopped";
        bookingTasks.value[taskIndex].endTime = new Date().toISOString();
      }

      // 调用API
      await bookingApi.stopBooking(taskId);
    } catch (error) {
      console.error("停止抢票任务失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const handleBookingSuccess = (taskId, data) => {
    // 更新任务状态
    const taskIndex = bookingTasks.value.findIndex(
      (task) => task.id === taskId
    );
    if (taskIndex > -1) {
      bookingTasks.value[taskIndex].status = "success";
      bookingTasks.value[taskIndex].endTime = new Date().toISOString();
    }

    // 添加到历史记录
    const result = parseBookingResult(data);
    bookingHistory.value.push({
      taskId,
      ...result,
    });

    // 清理Worker
    const worker = activeWorkers.value[taskId];
    if (worker) {
      worker.terminate();
      delete activeWorkers.value[taskId];
    }
  };

  const handleBookingError = (taskId, error) => {
    // 更新任务状态
    const taskIndex = bookingTasks.value.findIndex(
      (task) => task.id === taskId
    );
    if (taskIndex > -1) {
      bookingTasks.value[taskIndex].status = "error";
      bookingTasks.value[taskIndex].endTime = new Date().toISOString();
      bookingTasks.value[taskIndex].error = error;
    }

    // 添加到历史记录
    bookingHistory.value.push({
      taskId,
      success: false,
      message: error,
      data: null,
      timestamp: new Date().toISOString(),
    });

    // 清理Worker
    const worker = activeWorkers.value[taskId];
    if (worker) {
      worker.terminate();
      delete activeWorkers.value[taskId];
    }
  };

  const handleBookingRetry = (taskId, data) => {
    const taskIndex = bookingTasks.value.findIndex(
      (task) => task.id === taskId
    );
    if (taskIndex > -1) {
      bookingTasks.value[taskIndex].retryCount = data.count;
      bookingTasks.value[taskIndex].lastError = data.error;
    }
  };

  const clearHistory = () => {
    bookingHistory.value = [];
  };

  return {
    // 状态
    bookingTasks,
    bookingHistory,
    loading,

    // 计算属性
    activeTaskCount,
    successCount,
    failureCount,
    successRate,

    // 方法
    startBooking,
    stopBooking,
    clearHistory,
  };
});
